import { parse } from 'node:url';
import type { Request, Response } from 'express';
import type { LessonItem } from './data.d';
// @ts-ignore
import lessonDataJson from '../../../mock/lesson-data.json';

const lessonData: LessonItem[] = lessonDataJson as LessonItem[];

function getLessonList(req: Request, res: Response, u: string) {
  console.log('[Mock] getLessonList called, url:', req.url);
  let realUrl = u;
  if (
    !realUrl ||
    Object.prototype.toString.call(realUrl) !== '[object String]'
  ) {
    realUrl = req.url;
  }
  const { current = 1, pageSize = 10 } = req.query;
  const params = parse(realUrl, true).query as unknown as {
    current?: number;
    pageSize?: number;
    来源?: string;
    失效工序?: string;
    工厂?: string;
    项目名称?: string;
    LessonID?: string;
    发生时间?: string[];
  };

  let dataSource = [...lessonData];

  // 过滤条件（支持模糊匹配，兼容手动输入和枚举选择）
  if (params.来源) {
    dataSource = dataSource.filter((item) =>
      item.来源.includes(params.来源 || ''),
    );
  }
  if (params.失效工序) {
    dataSource = dataSource.filter((item) =>
      item.失效工序.includes(params.失效工序 || ''),
    );
  }
  if (params.工厂) {
    dataSource = dataSource.filter((item) =>
      item.工厂.includes(params.工厂 || ''),
    );
  }
  if (params.项目名称) {
    dataSource = dataSource.filter((item) =>
      item.项目名称.includes(params.项目名称 || ''),
    );
  }
  if (params.LessonID) {
    dataSource = dataSource.filter((item) =>
      item.LessonID.includes(params.LessonID || ''),
    );
  }
  if (params.发生时间 && Array.isArray(params.发生时间) && params.发生时间.length === 2) {
    const [startDate, endDate] = params.发生时间;
    dataSource = dataSource.filter((item) => {
      const itemDate = item.发生时间;
      return itemDate >= startDate && itemDate <= endDate;
    });
  }

  // 分页
  const total = dataSource.length;
  const pageNum = (current as number) || 1;
  const pageSizeNum = (pageSize as number) || 10;
  const start = (pageNum - 1) * pageSizeNum;
  const end = start + pageSizeNum;
  dataSource = dataSource.slice(start, end);

  const result = {
    data: dataSource,
    total: total,
    success: true,
    pageSize: pageSizeNum,
    current: pageNum,
  };

  return res.json(result);
}

export default {
  'GET /api/lesson/list': getLessonList,
};

